package service

import (
	"fanqiechaodan-blog/config"
	"fanqiechaodan-blog/dao"
	"fanqiechaodan-blog/models"
	"html/template"
)

func GetPostDetail(pid int) (*models.PostRes, error) {
	post, err := dao.GetPostDetailById(pid)
	if err != nil {
		return nil, err
	}
	categoryName, err := dao.GetCategoryNameById(post.CategoryId)
	if err != nil {
		return nil, err
	}
	userName, err := dao.GetUserNameById(post.UserId)
	if err != nil {
		return nil, err
	}
	return &models.PostRes{
		Viewer:       config.Cfg.Viewer,
		SystemConfig: config.Cfg.System,
		Article: models.PostMore{
			Pid:          post.Pid,
			Title:        post.Title,
			Slug:         post.Slug,
			Content:      template.HTML(post.Content),
			CategoryId:   post.CategoryId,
			CategoryName: categoryName,
			UserId:       post.UserId,
			UserName:     userName,
			ViewCount:    post.ViewCount,
			Type:         post.Type,
			CreateAt:     models.DateDay(post.CreateAt),
			UpdateAt:     models.DateDay(post.UpdateAt),
		},
	}, nil
}

func Writing() (*models.WritingRes, error) {
	categorys, err := dao.GetAllCategory()
	if err != nil {
		return nil, err
	}
	return &models.WritingRes{
		Title:     config.Cfg.Viewer.Title,
		CdnURL:    config.Cfg.System.CdnURL,
		Categorys: categorys,
	}, nil
}

func FindPostPigeonhole() (*models.PigeonholeRes, error) {
	categorys, err := dao.GetAllCategory()
	if err != nil {
		return nil, err
	}
	posts, err := dao.GetAllPost()
	if err != nil {
		return nil, err
	}
	m := make(map[string][]models.Post)
	for _, post := range posts {
		at := post.CreateAt
		month := at.Format("2006-01")
		m[month] = append(m[month], post)
	}
	return &models.PigeonholeRes{
		Viewer:       config.Cfg.Viewer,
		SystemConfig: config.Cfg.System,
		Categorys:    categorys,
		Lines:        m,
	}, nil
}

func SearchPost(condition string) ([]models.SearchResp, error) {
	posts, err := dao.GetPostByCondition(condition)
	if err != nil {
		return nil, err
	}
	var res []models.SearchResp
	for _, post := range posts {
		res = append(res, models.SearchResp{
			Pid:   post.Pid,
			Title: post.Title,
		})
	}
	return res, nil
}

func SavePost(post *models.Post) error {
	return dao.SavePost(post)
}

func UpdatePost(post *models.Post) error {
	return dao.UpdatePost(post)
}
